import type { ConfigEnv } from 'vite'
import { loadEnv, defineConfig } from 'vite'

import { resolve } from 'path'

import { getPluginsList } from './build/plugins'

// 路径查找
const pathResolve = (dir: string): string => {
    return resolve(__dirname, '.', dir)
}

// 设置别名
const alias: Record<string, string> = {
    '@': pathResolve('src'),
    '@build': pathResolve('build'),
    '@types': pathResolve('types'),
}

export default ({ command, mode }: ConfigEnv) => {
    const dirRoot = process.cwd()
    const env = loadEnv(mode, dirRoot)

    const ENV_BUILD = command === 'build' // command 判断运行环境  build serve

    return defineConfig({
        root: `${dirRoot}`,
        base: env.VITE_PUBLIC_PATH,
        resolve: {
            alias,
        },
        plugins: getPluginsList(ENV_BUILD),
        server: {
            https: false, // 是否开启 https
            port: 9966, //启动端口
            host: '0.0.0.0',
            open: true,
        },
        build: {
            sourcemap: false, //默认false
            outDir: 'webSite', // 构建输出的主目录
            assetsDir: 'assets', //默认assets,静态资源存放路径（相对于build.outDir）
            rollupOptions: {
                input: {
                    main: pathResolve('main/index.html'),
                    share: pathResolve('share/index.html'),
                },
            },
            // 消除打包大小超过500kb警告,改为2000kb
            chunkSizeWarningLimit: 2048,
            // terserOptions: {
            //     compress: {
            //         drop_console: !ENV_BUILD, // 打包环境移除console  默认false
            //         drop_debugger: !ENV_BUILD, // 打包环境移除debug  默认true
            //     },
            // },
            // minify: 'terser', // 默认esbuild  效率比terser高20~40倍
        },
    })
}
